<?
require("abstractClass.php");
class Model extends AbstractModel {
	private $variableFieldSet;
	private $arrayDataFieldSet;
	private $variableButtonControl;
	private $variableNoFieldSet;
	static public $checkValidate = array();
	public $variableOptionFormName;
	public $variableOptionFormButton;
	
	//########################+ModelTable+########################//
	private $arrayHeader = array();
	private $arrayColumn = array();
	private $arrayLinkJavascript = array();
	private $arrayParamLinkJavascript = array();
	private $singleQote;
	public $numberPageScope;
	public $numberTableScope;
	public $numPage;
	private $divInnerID;
	
	public $arrayParamFunctionView = array();
	public $arrayParamFunctionDelete = array();
	public $arrayParamFunctionEdit = array();
	public $functionViewName;
	public $functionDeleteName;
	public $functionEditName;
	
	public function setModelNumberPageScope($number = 0){
		$this->numberPageScope = $number;
	}
	
	public function setModelNumberTableScope($number = 0){
		$this->numberTableScope = $number;
	}
	
	public function setModelColumn($column){
		$this->arrayColumn = $column;
	}
	
	public function setModelHeader($header){
		$this->arrayHeader =$header;
	}
	
	public function setModelLinkJavascript($link){
		$this->arrayLinkJavascript = $link;
	}
	
	public function setModelParamLinkJavascript($param,$singleQote=true){
		$this->arrayParamLinkJavascript = $param;
		$this->singleQote = $singleQote;
	}
	
	public function setModelSQLTable($sql){
		//if($_GET["pagination"] == true){
			$result = Database::query($sql);
			$num = Database::numRows($result);
			$this->numPage = $num/$this->numberTableScope;
			if($_POST["page"] == 1 || $_POST["page"] == ""){
				$sql .= " limit 0,".$this->numberTableScope."";
			}else{
				if($this->numberTableScope)
				$sql .= " limit ".(($this->numberTableScope*$_POST["page"])-1).",".$this->numberTableScope."";
			}
			//echo $sql;
			$result = Database::query($sql);
		//}
		
		if(is_array($this->arrayHeader)){
			$header = array();
			$arrayHeader = array();
			$rowID = 0;
			while($arrayResult = Database::fetchArray($result)){
				foreach($this->arrayHeader as $keyHeader => $valueHeader){									
					//if($arrayResult[$keyHeader] != ""){
							$header[$rowID][$keyHeader] = $arrayResult[$keyHeader];
							if(!in_array($keyHeader,$arrayHeader)){
								$arrayHeader[] = $keyHeader;	
							}
					//}
				}
				$rowID++;
			}
			
			$html = '<table class="table table-striped" aria-describedby="DataTables_Table_0_info">';
				$html .= '<thead>';
					$html .= '<tr>';
					foreach($this->arrayHeader as $keyHeader => $valueHeader){
						if(in_array($keyHeader,$arrayHeader)){		
								$html .= '<th>'.$valueHeader.'</th>';
						}
					}
					$html .= '<tr>';
				$html .= '</thead>';
				$html .= '<tbody>';				
				
				foreach($header as $keyHeader => $valueHeader){
					$html .= '<tr>';
					foreach($valueHeader as $keyHeader2 => $valueHeader2){
						$html .= '<td';
						if($this->arrayColumn[$keyHeader2] == "edit"){
								$valueHeader2 = '<i class="icon-edit icon-white"></i>Edit';
								if($this->arrayLinkJavascript[$keyHeader2]!=""){
									$param = "";
									$i = 1;
									if($this->arrayParamLinkJavascript[$keyHeader2] != ""){										
										foreach($this->arrayParamLinkJavascript[$keyHeader2]  as $valueParam){
											if(!in_array($valueParam, $this->arrayParamFunctionEdit)){
												$this->arrayParamFunctionEdit[] = $valueParam;
											}
											$data = $valueHeader[$valueParam];
											if($this->singleQote){
													$data = "'".$data."'";
											}
											$param .= $data;
											if($i != count($this->arrayParamLinkJavascript[$keyHeader2])){
												$param .= ',';	
											}
											$i++;
										}
									}
									$valueHeader2 = '<a class="btn btn-info" href="javascript:'.$this->arrayLinkJavascript[$keyHeader2].'('.$param.')"><i class="icon-edit icon-white"></i>Edit</a>';
									$this->functionEditName = $this->arrayLinkJavascript[$keyHeader2];
								}
							$html .= ' style="text-align:center"';
						}else if($this->arrayColumn[$keyHeader2] == "delete"){
								$valueHeader2 = '<i class="icon-trash icon-white"></i>Delete';
								if($this->arrayLinkJavascript[$keyHeader2]!=""){
									$param = "";
									$i = 1;
									if($this->arrayParamLinkJavascript[$keyHeader2] != ""){										
										foreach($this->arrayParamLinkJavascript[$keyHeader2]  as $valueParam){
											if(!in_array($valueParam, $this->arrayParamFunctionDelete)){
												$this->arrayParamFunctionDelete[] = $valueParam;
											}
											$data = $valueHeader[$valueParam];
											if($this->singleQote){
													$data = "'".$data."'";
											}
											$param .= $data;
											if($i != count($this->arrayParamLinkJavascript[$keyHeader2])){
												$param .= ',';	
											}
											$i++;
										}
									}
									$valueHeader2 = '<a class="btn btn-danger" href="javascript:'.$this->arrayLinkJavascript[$keyHeader2].'('.$param.')"><i class="icon-trash icon-white"></i>Delete</a>';
									$this->functionDeleteName = $this->arrayLinkJavascript[$keyHeader2];
								}
							$html .= ' style="text-align:center"';
						}else if($this->arrayColumn[$keyHeader2] == "view"){
								$valueHeader2 = '<i class="icon-zoom-in icon-white"></i>View';
								if($this->arrayLinkJavascript[$keyHeader2]!=""){
									$param = "";
									$i = 1;
									if($this->arrayParamLinkJavascript[$keyHeader2] != ""){										
										foreach($this->arrayParamLinkJavascript[$keyHeader2]  as $valueParam){
											if(!in_array($valueParam, $this->arrayParamFunctionView)){
												$this->arrayParamFunctionView[] = $valueParam;
											}
											$data = $valueHeader[$valueParam];
											if($this->singleQote){
													$data = "'".$data."'";
											}
											$param .= $data;
											if($i != count($this->arrayParamLinkJavascript[$keyHeader2])){
												$param .= ',';	
											}
											$i++;
										}
									}
									$valueHeader2 = '<a class="btn btn-success" href="javascript:'.$this->arrayLinkJavascript[$keyHeader2].'('.$param.')"><i class="icon-zoom-in icon-white"></i>View</a>';
									$this->functionViewName = $this->arrayLinkJavascript[$keyHeader2];
								}
							$html .= ' style="text-align:center"';
						}
						$html .= '>'.$valueHeader2.'</td>';
					}
					$html .= '</tr>';				
				}
				$html .= '</tbody>';
			$html .= '</table>';
			
			$paggingData = '<div class="row-fluid">';
				$paggingData .= '<div class="span12">';
					$paggingData .= '<div class="dataTables_info" id="DataTables_Table_0_info">Showing 11 to 20 of 32 entries</div>';
				$paggingData .= '</div>';
				$paggingData .= '<div class="span12 center">';
					$paggingData .= '<div class="dataTables_paginate paging_bootstrap pagination">';
						$paggingData .= '<ul>';
							if($_POST["page"] == ""){
								$_POST["page"] = 1;
							}
							$paggingData .= '<li class="prev"><a href="javascript:previous()">← Previous</a></li>';
							for($i=1;$i<=$this->numPage;$i++){
									$active = "";
									if($_POST["page"] == $i){
										$active .= ' class="active"';
										$numberActive = $i;
									}
									$paggingData .= '<li'.$active.' id="pg_'.$i.'"><a href="javascript:pagination('.$i.')">'.$i.'</a></li>';
							}
							/*$paggingData .= '<li class="active"><a href="javascript:pagination(1)">1</a></li>';
							$paggingData .= '<li><a href="javascript:pagination(2)">2</a></li>';
							$paggingData .= '<li><a href="#">3</a></li>';
							$paggingData .= '<li><a href="#">31</a></li>';
							$paggingData .= '<li><a href="#">32</a></li>';
							$paggingData .= '<li><a href="#">33</a></li>';*/
							$paggingData .= '<li class="next"><a href="javascript:next()">Next → </a></li>';
						$paggingData .= '</ul>';
					$paggingData .= '</div>';
				$paggingData .= '</div>';
			$paggingData .= '</div>';
			
			$html .= $paggingData;
		}	
		echo $html;
		
	}
	
	public function setModelDivInnerID($id){
		$this->divInnerID = $id;
	}

	public function createFunctionJavascriptControlTable(){		
		$htmlJavascript = '<script language="JavaScript">';
			//##################+function View+################//
			$htmlJavascript .= 'function '.$this->functionViewName.'(';
			$i = 1;
			$param = "";
			foreach ($this->arrayParamFunctionView as $value) {
				$htmlJavascript .= $value;
				$param .= '"'.$value.'="+'.$value;
				if($i != count($this->arrayParamFunctionView)){
					$htmlJavascript .= ',';
					$param .= '+"&"+';
				}
				$i++;
			}
			$htmlJavascript .= ')';
			$htmlJavascript .= '{';
				$htmlJavascript .= '$.ajax({';
					$htmlJavascript .= 'type:"POST",';
					$htmlJavascript .= 'url: "ajaxLoadPage.php?class='.THIS_CLASS.'&function=view",';
					$htmlJavascript .= 'data: '.$param.',';
					$htmlJavascript .= 'success: function(data2){';
						$htmlJavascript .= '$(\'div[id="'.$this->divInnerID.'"]\').html(data2);';
					$htmlJavascript .= '}';
				$htmlJavascript .= '});';
			$htmlJavascript .= '}';
			
			//##################+function Edit+################//
			$htmlJavascript .= 'function '.$this->functionEditName.'(';
			$i = 1;
			$param = "";
			foreach ($this->arrayParamFunctionEdit as $value) {
				$htmlJavascript .= $value;
				$param .= '"'.$value.'="+'.$value;
				if($i != count($this->arrayParamFunctionEdit)){
					$htmlJavascript .= ',';
					$param .= '+"&"+';
				}
				$i++;
			}
			$htmlJavascript .= ')';
			$htmlJavascript .= '{';
				$htmlJavascript .= '$.ajax({';
					$htmlJavascript .= 'type:"POST",';
					$htmlJavascript .= 'url: "ajaxLoadPage.php?class='.THIS_CLASS.'&function=form",';
					$htmlJavascript .= 'data: '.$param.',';
					$htmlJavascript .= 'success: function(data2){';
						$htmlJavascript .= '$(\'div[id="'.$this->divInnerID.'"]\').html(data2);';
					$htmlJavascript .= '}';
				$htmlJavascript .= '});';
			$htmlJavascript .= '}';
			
			//##################+function Delete+################//
			$htmlJavascript .= 'function '.$this->functionDeleteName.'(';
			$i = 1;
			$param = "";
			foreach ($this->arrayParamFunctionView as $value) {
				$htmlJavascript .= $value;
				$param .= '"'.$value.'="+'.$value;
				if($i != count($this->arrayParamFunctionView)){
					$htmlJavascript .= ',';
					$param .= '+"&"+';
				}
				$i++;
			}
			$htmlJavascript .= ')';
			$htmlJavascript .= '{';
				$htmlJavascript .= '$.ajax({';
					$htmlJavascript .= 'type:"POST",';
					$htmlJavascript .= 'url: "ajaxLoadPage.php?class='.THIS_CLASS.'&function=delete",';
					$htmlJavascript .= 'data: '.$param.',';
					$htmlJavascript .= 'success: function(data2){';
						$htmlJavascript .= '$(\'div[id="'.$this->divInnerID.'"]\').html(data2);';
						
						$htmlJavascript .= '$.ajax({';
							$htmlJavascript .= 'type:"POST",';
							$htmlJavascript .= 'url: "ajaxLoadPage.php?class='.THIS_CLASS.'&function=table",';
							//$htmlJavascript .= 'data: '.$param.',';
							$htmlJavascript .= 'success: function(data2){';
								$htmlJavascript .= '$(\'div[id="'.$this->divInnerID.'"]\').html(data2);';						
							$htmlJavascript .= '}';
						$htmlJavascript .= '});';
											
					$htmlJavascript .= '}';
				$htmlJavascript .= '});';
			$htmlJavascript .= '}';
		$htmlJavascript .= '</script>';
		echo $htmlJavascript;
	}
	//########################+++++++++++########################//
	
	public function setModelOptionFormName($optionFormName = ""){
		$this->variableOptionFormName = $optionFormName;
	}
	
	public function setModelOptionFormButton($optionFormButton = array()){
		$button = '<div class="box-icon">';
		foreach ($optionFormButton as $key => $value) {
			if($key == "form"){
				$button .= '<a title="เพิ่มข้อมูล" id="form_a_'.THIS_CLASS.'" href="javascript:'.$value.'" class="btn btn-setting btn-round"><i id="form_i_'.THIS_CLASS.'" class=" icon-plus"/></a>';
			}else if($key == "table"){
				$button .= '<a title="ค้นหาข้อมูล" id="table_a_'.THIS_CLASS.'" href="javascript:'.$value.'" class="btn btn-setting btn-round"><i id="table_i_'.THIS_CLASS.'" class="icon-search"/></a>';
			}else if($key == "minimize"){
				$button .= '<a title="ซ่อน" id="minimize_a_'.THIS_CLASS.'" href="javascript:'.$value.'" class="btn btn-minimize btn-round"><i id="minimize_i_'.THIS_CLASS.'" class="icon-chevron-up"/></a>';
			}
		}
		$button .= '</div>';
		$this->variableOptionFormButton = $button;
	}
	
	public function setModelFieldSet($arrayFieldSet = array()){
		$this->variableFieldSet = $arrayFieldSet;
	}
	
	public function setModelButtonControlInput($arrayButton = array()){
		$this->variableButtonControl = $arrayButton;
	}
	
	public function setModelButtonControlOutput($arrayButton = array()){
		$this->variableButtonControl = $arrayButton;
	}
	
	public function setDataFieldSet(){
		$data = "";
		if(is_array($this->variableFieldSet)){
			foreach ($this->variableFieldSet as $keyf => $valuef){
				if(isset($this->arrayDataFieldSet[$keyf])){
					$data .= '<fieldset id="FS_'.$keyf.'"><legend id="L_'.$keyf.'">'.$valuef.'</legend>';
						$data .= $this->arrayDataFieldSet[$keyf];
					$data .= '</fieldset>';	
				}	
			}
		}
		return $data;
	}
	
	public function validateData($data){
		$boolCheck = true;
		
		$htmlJavascript = '<script language="JavaScript" src="jquery/jquery-1.9.1.js"></script>';
		$htmlJavascript .= '<script language="JavaScript">';
		$htmlJavascript .= 'function messageAlert(){';
		foreach($data as $key => $value){
			$boolCheck = false;
			foreach($value as $value2){			
				$htmlJavascript .= '$(\'[name="'.$key.'"]\').parent().append(\'<div class="validateAlert1" style="width:100%;color:red;">'.$value2.'</div>\');';
			}
		}
		$htmlJavascript .= '}';
		$htmlJavascript .= '</script>';			
		echo $htmlJavascript;
		return $boolCheck;
	}
	
	public function submitDataForm(){
		$htmlJavascript = '<script language="JavaScript">';
		$htmlJavascript .= 'function submitForm_'.THIS_CLASS.'(enctype){';
			$htmlJavascript .= '$(\'.validateAlert1\').remove();';
			$htmlJavascript .= 'var form = $("#form_'.THIS_CLASS.'");';
			//$htmlJavascript .= 'if(valid_'.THIS_CLASS.'()){';
				$htmlJavascript .= 'if(enctype){';
					$htmlJavascript .= 'var formData = new FormData(form[0]);';
					$htmlJavascript .= '$.ajax({';
						$htmlJavascript .= 'url:form.attr("action"),';
						$htmlJavascript .= 'type: "POST",';
						$htmlJavascript .= 'data: formData,';
						$htmlJavascript .= 'async: false,';
						$htmlJavascript .= 'success: function (data) {';
						$htmlJavascript .= '$(\'#errorMessage\').html(data);';
						$htmlJavascript .= 'messageAlert();';
						$htmlJavascript .= '},';
						$htmlJavascript .= 'cache: false,';
						$htmlJavascript .= 'contentType: false,';
						$htmlJavascript .= 'processData: false';
					$htmlJavascript .= '});';
				$htmlJavascript .= '}else{';
					$htmlJavascript .= '$.ajax({';
						$htmlJavascript .= 'url:form.attr("action"),';
						$htmlJavascript .= 'type: "POST",';
						$htmlJavascript .= 'data: form.serialize(),';
						$htmlJavascript .= 'success: function (data) {';						
						$htmlJavascript .= '$(\'#errorMessage\').html(data);';
						$htmlJavascript .= 'messageAlert();';
						$htmlJavascript .= '}';
					$htmlJavascript .= '});';
				$htmlJavascript .= '}';
			//$htmlJavascript .= '}';
			$htmlJavascript .= 'return false;';
		$htmlJavascript .= '}';
		$htmlJavascript .= '</script>';
		echo $htmlJavascript;
	}
	
	public function setDataButtonControl(){		
		if(is_array($this->variableButtonControl)){
			$data = '<div class="form-actions">';
			foreach ($this->variableButtonControl as $key => $value) {
				$data .= '<span id="span_'.$key.'">';
				$data .= '<button id="'.$key.'" ';
				if($value[1]!=""){
					$data .= 'type="'.$value[1].'" ';
				}else{
					$data .= 'type="button" ';
				}
				if($key == 'btn_save'){
					$data .= 'class="btn btn-small btn-primary" ';
				}else{
					$data .= 'class="btn btn-small" ';
				}
				if($value[2]!=""){
					$data .= 'onclick="'.$value[2].'"';
				}
				$data .= '>';
				if($value[0]!=""){
					$data .= $value[0];
				}else{
					$data .= 'No Name';
				}
				$data .= '</button>';
				$data .= '</span> ';
			}
			$data .= '</div>';		
			return $data;
		}		
		
	}
	
	public function setModelOutput($outputData = ""){
		$lineTableFirst = array();
		$defaultLabel = 10;
		$maxlength = 100;
		$defaultLabel2 = 100;
		$model = array();
		$label = array();
		$output = array();
		$outputWidth = array();
		if($outputData == "" || !is_array($outputData)){
			$outputData = array();
		}
		foreach ($outputData as $key => $value) {
			$this->variableNoFieldSet = $key;
			$lineTableFirst[$key] = '<table class="'.$table_input_class.'" width="100%">';
			$i = $key;
			foreach ($value as $key2 => $value2) {
				$model[$i] = '<tr class="tr_input">';
				foreach ($value2 as $key3 => $value3) {
					if($key3 == 'label'){
						$label[$i]['label'] = $value3;
					}else if($key3 == 'labelWidth'){
						$labelWidth[$i]['labelWidth'] = $value3;
					}else if($key3 == 'output'){
						$output[$i]['output'] = $value3;
					}else if($key3 == 'outputWidth'){
						$outputWidth[$i]['outputWidth'] = $value3;
					}
				}
				$colspan = "";
			
				if($label[$i]['label'] != "" && $labelWidth[$i]['labelWidth'] != ""){					
					$model[$i] .= '<td class="td_input" style="width:'.$labelWidth[$i]['labelWidth'].'%; text-align: right;"><div class="prefix">'.$label[$i]['label'].' :</div></td>';
				}else if($label[$i]['label'] !="" && $labelWidth[$i]['labelWidth'] == ""){
					$model[$i] .= '<td class="td_input" style="width:'.$defaultLabel.'%; text-align: right;"><div class="prefix">'.$label[$i]['label'].' :</div></td>';
				}else{
					$colspan = 'colspan="2"';
				}
		
				if($label[$i]['label'] == ""){
					$width = $defaultLabel2;
				}else if($labelWidth[$i]['labelWidth'] == ""){
					$width = $maxlength - $defaultLabel;			
				}else{
					$width = $maxlength - floatval($labelWidth[$i]['labelWidth']);
				}
				if($output[$i]['output'] != ""){
					$model[$i] .= '<td class="td_input" '.$colspan.' style="width:'.$width.'%;"><div>'.$output[$i]['output'].'</div></td>';
				}else{
					$model[$i] .= '<td class="td_input"  style="width:'.$width.'%;"><div></div></td>';
				}
				$model[$i] .= '</tr>';
				
				$lineTableFirst[$key] .= $model[$i];
			}
			$lineTableFirst[$key] .= '</table>';		
		}
		
		$this->arrayDataFieldSet = $lineTableFirst;
		
		if($this->variableNoFieldSet == 'NONE'){
			$data = $lineTableFirst["NONE"];
		}else{
			$data = $this->setDataFieldSet();
		}
		
		$data .= $this->setDataButtonControl();
				
		$this->dataOutput = $data;
	}

	public function setModelInput($inputData = array()){
		$defaultLabel = 10;
		$maxlength = 100;
		$defaultLabel2 = 100;
		$label = array();
		$labelWidth = array();
		$input = array();
		$inputWidth = array();
		$model = array();
		$arrayValidate = array();
		$required = array();
		$lineTableFirst = array();
		$enctype = false;
		
		foreach ($inputData as $key8 => $value8) {			
			$this->variableNoFieldSet = $key8;
			//$lineTableFirst[$key8] = '<table class="table_input" width="100%">';
			$i = $key8;
			foreach ($value8 as $key => $value){
				$model[$i] = '<div class="control-group">';	
				foreach ($value as $key2 => $value2){
					if($key2 == 'label'){
						$label[$i]['label'] = $value2;
					}else if($key2 == 'labelWidth'){
						$labelWidth[$i]['labelWidth'] = $value2;
					}else if($key2 == 'input'){
						$input[$i]['input'] = $value2;
					}else if($key2 == 'inputWidth'){
						$inputWidth[$i]['inputWidth'] = $value2;
					}else if($key2 == 'required'){
						$required[$i]['required'] = $value2;
					}else if($key2 == 'enctype'){
						if($enctype == false){
							$enctype = ($value2=="")?false:true;
						}
					}
				}
				/////////////////////////****************************

				if($input[$i]['inputAuto']){
					$arrayValidate[$input[$i]['name']]['id'] = $input[$i]['id'];
					$arrayValidate[$input[$i]['name']]['required'] = $required[$i]['required'];
				}
				
				//////////////*************************
				$colspan = "";
				
				if($label[$i]['label'] != "" || $labelWidth[$i]['labelWidth'] != ""){
					$requiredData = "";
					if($required[$i]['required'] == 'true'){
						$requiredData = '*';
					}
					$model[$i] .= '<label class="control-label" for="typeahead"><div class="prefix"><span name="required['.$input[$i]['name'].']" class="required">'.$requiredData.'</span>'.$label[$i]['label'].' :</div></label>';
					
					if($input[$i]['input'] != ""){
						$model[$i] .= '<div class="controls">'.$input[$i]['input'].'</div>';
					}else{
						$model[$i] .= '<div class="controls"><div>';
					}
				}else{
					if($input[$i]['input'] != ""){
						$model[$i] .= '<div class="inner">'.$input[$i]['input'].'</div>';
					}else{
						$model[$i] .= '<div class="inner"><div>';
					}	
				}				
				
				$model[$i] .= '</div>';
							
				$lineTableFirst[$key8] .= $model[$i];
	
			}
			//$lineTableFirst[$key8] .= '</table>';
		}
		
		$this->enctype = $enctype;
		$this->arrayDataFieldSet = $lineTableFirst;
		$this->variableValidate = $arrayValidate;		

		if($this->variableNoFieldSet == 'NONE'){
			$data = $lineTableFirst["NONE"];
		}else{
			$data = $this->setDataFieldSet();
		}
		$data .= $this->setDataButtonControl();		
		
		$this->dataInput = $data;
	}
}
?>
